package com.lidx.back.statistics.dao.impl;

import com.lidx.back.statistics.commons.PageInfo;
import com.lidx.back.statistics.dao.ITeamResourceDao;
import com.lidx.back.statistics.entity.TeamResource;
import com.lidx.back.statistics.utils.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by chen on 2017/2/17.
 */
@Repository
public class TeamResourceDaoImpl implements ITeamResourceDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void insertTeamResource(TeamResource teamResource) {
        getSession().save(teamResource);
        getSession().flush();
    }

    @Override
    public List<TeamResource> findTeamResourceList() {
        return getSession().createQuery("from TeamResource").list();
    }

    @Override
    public TeamResource getTeamResourceById(int id) {
        return (TeamResource)getSession().get(TeamResource.class,id);
    }

    @Override
    public void deleteTeamResourceById(int id) {
        TeamResource tr = (TeamResource)getSession().get(TeamResource.class,id);
        getSession().delete(tr);
        getSession().flush();
    }

    @Override
    public void updateTeamResource(TeamResource teamResource) {
        getSession().update(teamResource);
    }

    @Override
    public PageInfo findTeamResourcePage(int pageNo, int pageSize,String resourceCategory) {
        StringBuilder sb = new StringBuilder("from TeamResource where 1 = 1");
        if(StringUtils.isNotBlank(resourceCategory)){
            sb.append(" and resourceCategory ='").append(resourceCategory).append("'");

        }
        sb.append(" order by saveDate desc");
        Query query = getSession().createQuery(sb.toString());
        final int offset = PageInfo.countOffset(pageSize, pageNo);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List list = query.list();
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNo(pageNo);
        pageInfo.setPageSize(pageSize);
        pageInfo.setList(list);
        long allRow = queryTRPageCount(resourceCategory);
        pageInfo.setAllRow(allRow);
        pageInfo.setTotalPage(PageInfo.countTotalPage(pageSize, allRow));
        return pageInfo;
    }

    private long queryTRPageCount(String resourceCategory) {
        StringBuilder sb = new StringBuilder("select count(1) from TeamResource where 1=1");
        if(StringUtils.isNotBlank(resourceCategory)){
            sb.append(" and resourceCategory ='").append(resourceCategory).append("'");
        }
        Query query = getSession().createQuery(sb.toString());
        return  (Long) query.list().get(0);
    }
}
